//
//  DetailsTableViewController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/3/1.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "DetailsTableViewController.h"
#import "ServiceTableViewCell.h"
#import "RegisteredViewController.h"
#import "TipsViewController.h"
#import "IntroduceViewController.h"
#import "DoctorListViewController.h"
#import "DataManager.h"
#import "LoginViewController.h"
#import "MedicalRecordViewController.h"
#import <Masonry.h>
#import <MapKit/MapKit.h>

#define kShared [DataManager defaultManager]
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height

@interface DetailsTableViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>

@property(nonatomic,strong)NSMutableArray *hospitalArray;
@property(nonatomic,strong)NSMutableArray *annotationArray;
@property(nonatomic,strong)NSMutableArray *imageArray;
//用户当前位置
@property (nonatomic,strong) CLLocation *currentUserLocation;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,strong) NSString *startString;
@end

@implementation DetailsTableViewController
- (CLGeocoder *)geocoder{
    
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (CLLocation *)currentUserLocation
{
    if(!_currentUserLocation)
    {
        _currentUserLocation = [[CLLocation alloc] init];
    }
    return  _currentUserLocation;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *string = nil;
    //判断是否是普通用户，医生没有收藏功能
    if([kShared.userType isEqualToString:@"普通用户"])
    {
        //判断此医院当前用户是否收藏过
        if([kShared.collectHospitalArray containsObject:self.hospital])
        {
            string = @"取消收藏";
        }
        else
        {
            string = @"收藏";
        }
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:string style:UIBarButtonItemStyleDone target:self action:@selector(didClickCollect:)];
    }
    //3.开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"医院主页";
    self.view.backgroundColor = [UIColor whiteColor];
    //隐藏tabBar
    self.tabBarController.tabBar.hidden = YES;
    //创建定位对象
    [self startUP];
    [self detailsViews];
    [self detailsTableVIews];
}

//创建定位对象
- (void)startUP
{
    //1.创建定位对象
    self.locationManager = [[CLLocationManager alloc]init];
    //访问授权
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];
    //2.设置代理
    self.locationManager.delegate = self;
    
}

//点击右边按钮的事件
- (void)didClickCollect:(UIBarButtonItem *)sender
{
    //判断点击的是收藏还是取消收藏
    if([sender.title isEqualToString:@"收藏"])
    {
        //如果点击的是收藏，就将当前医院信息收藏到数据库中
        [kShared.collectHospitalArray addObject:self.hospital];
        [[AVUser currentUser] setObject:kShared.collectHospitalArray forKey:@"collectHospital"];
        [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if(succeeded)
            {
                sender.title = @"取消收藏";
            }
        }];
    }
    else
    {
        //如果点击的是取消收藏，就将当前医院信息从数据库中删除
        [kShared.collectHospitalArray removeObject:self.hospital];
        [[AVUser currentUser] setObject:kShared.collectHospitalArray forKey:@"collectHospital"];
        [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if(succeeded)
            {
                sender.title = @"收藏";
            }
        }];
    }
    
}

// ---------------------------        View layout
- (void)detailsViews
{
    
    UIView *views = [[UIView alloc]init];
    views.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 280);
    views.backgroundColor = [UIColor grayColor];
    views.alpha = 0.2;
    self.tableView.tableHeaderView = views;
    //---------------------------------------------------------------医院路线布局
    UIView *DefuView = [[UIView alloc] init];
    DefuView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:DefuView];
    [DefuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.left.offset(0);
        make.size.mas_equalTo(CGSizeMake(kWidth, 100));
    }];
    
    //医院名字
    UILabel *hospitalName = [[UILabel alloc] init];
    hospitalName.font = [UIFont systemFontOfSize:15];
    hospitalName.text = self.hospital.hospitalName;
    [DefuView addSubview:hospitalName];
    [hospitalName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(20);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.4, 30));
    }];
    
    //医院等级
    UILabel *hospitaLevel = [[UILabel alloc] init];
    hospitaLevel.backgroundColor = [UIColor grayColor];
    hospitaLevel.font = [UIFont systemFontOfSize:14];
    hospitaLevel.textAlignment = NSTextAlignmentCenter;
    hospitaLevel.alpha = 0.3;
    hospitaLevel.text = self.hospital.hospitalLevel;
    hospitaLevel.layer.borderWidth = 0.1;
    hospitaLevel.layer.borderColor = [UIColor darkGrayColor].CGColor;
    hospitaLevel.layer.cornerRadius = 10.0;
    hospitaLevel.layer.masksToBounds = YES;
    [DefuView addSubview:hospitaLevel];
    [hospitaLevel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(kWidth * 0.4 + 20);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.3, 25));
    }];
    
    //医院地址
    UILabel *hospitaAddress = [[UILabel alloc] init];
    hospitaAddress.font = [UIFont systemFontOfSize:14];
    hospitaAddress.alpha = 0.5;
    hospitaAddress.text = self.hospital.hospitalAddress;
    [DefuView addSubview:hospitaAddress];
    [hospitaAddress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(60);
        make.left.offset(10);
        make.size.mas_equalTo(CGSizeMake(kWidth * 0.7, 30));
    }];
    
    UIButton *route = [UIButton buttonWithType:UIButtonTypeSystem];
    [route setTitle:@"查看路线" forState:UIControlStateNormal];
    [DefuView addSubview:route];
    [route mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(75);
        make.right.offset(-10);
        make.size.mas_equalTo(CGSizeMake(70, 15));
    }];
    
    UIImageView *routeImage = [UIImageView new];
    routeImage.image = [UIImage imageNamed:@"H8.png"];
    [DefuView addSubview:routeImage];
    [routeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.right.offset(-10);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    //添加隐藏View (查看路线)
    UIView *routePoint = [[UIView alloc] init];
    routePoint.backgroundColor = [UIColor whiteColor];
    routePoint.alpha = 0.1;
    [routePoint setUserInteractionEnabled:YES];
    [DefuView addSubview:routePoint];
    [routePoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.right.offset(-10);
        make.size.mas_equalTo(CGSizeMake(75, 75));
    }];
    
    //添加点击手势 (查看路线)
    UITapGestureRecognizer *routeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(routeAction:)];
    [routeTap setNumberOfTouchesRequired:1];
    [routePoint addGestureRecognizer:routeTap];
    
//

    //----------------------------------------------------------------医院信息布局
    UIView *DopaView = [UIView new];
    DopaView.frame = CGRectMake(0, 140, CGRectGetWidth(self.view.bounds), 120);
    DopaView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:DopaView];
    
    
    UIButton *information = [UIButton buttonWithType:UIButtonTypeSystem];
    information.backgroundColor = [UIColor whiteColor];
    [information setTitle:@"医院信息" forState:UIControlStateNormal];
    [DopaView addSubview:information];
    [information mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(10);
        make.size.mas_equalTo(CGSizeMake(70, 20));
    }];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 40, CGRectGetWidth(self.view.bounds), 2);
    lineView.backgroundColor = [UIColor grayColor];
    lineView.alpha = 0.1;
    [DopaView addSubview:lineView];
    
    UIButton *introduce = [UIButton buttonWithType:UIButtonTypeSystem];
    introduce.backgroundColor = [UIColor whiteColor];
    introduce.titleLabel.textAlignment = NSTextAlignmentCenter;
    [introduce setTitle:@"医院介绍" forState:UIControlStateNormal];
    [DopaView addSubview:introduce];
    [introduce mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-10);
        make.left.offset(kWidth * 0.19);
        make.size.mas_equalTo(CGSizeMake(70, 15));
    }];
    
    UIImageView *introduceImage = [UIImageView new];
    introduceImage.image = [UIImage imageNamed:@"H6.png"];
    [DopaView addSubview:introduceImage];
    [introduceImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-30);
        make.left.offset(kWidth * 0.25);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    
    UIButton *tips = [UIButton buttonWithType:(UIButtonTypeSystem)];
    tips.titleLabel.textAlignment = NSTextAlignmentCenter;
    [tips setTitle:@"就诊贴士" forState:UIControlStateNormal];
    [DopaView addSubview:tips];
    [tips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-10);
        make.right.offset(-(kWidth * 0.19));
        make.size.mas_equalTo(CGSizeMake(70, 15));
    }];
    
    UIImageView *tipsImage = [UIImageView new];
    tipsImage.image = [UIImage imageNamed:@"H11.png"];
    [DopaView addSubview:tipsImage];
    [tipsImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-30);
        make.right.offset(-(kWidth * 0.25));
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    //添加隐藏View (医院介绍)
    UIView *introducePoint = [[UIView alloc] init];
    introducePoint.backgroundColor = [UIColor whiteColor];
    introducePoint.alpha = 0.1;
    [introducePoint setUserInteractionEnabled:YES];
    [DopaView addSubview:introducePoint];
    [introducePoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-10);
        make.left.offset(kWidth * 0.19);
        make.size.mas_equalTo(CGSizeMake(70, 50));
    }];
    
    //添加点击手势 (医院介绍)
    UITapGestureRecognizer *introduceTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(introduceAction:)];
    [introduceTap setNumberOfTouchesRequired:1];
    [introducePoint addGestureRecognizer:introduceTap];
    
    
    //添加隐藏View (就诊贴士)
    UIView *tipsPoint = [[UIView alloc] init];
    tipsPoint.backgroundColor = [UIColor whiteColor];
    tipsPoint.alpha = 0.1;
    [tipsPoint setUserInteractionEnabled:YES];
    [DopaView addSubview:tipsPoint];
    [tipsPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-10);
        make.right.offset(-(kWidth * 0.21));
        make.size.mas_equalTo(CGSizeMake(70, 50));
    }];
    
    //添加点击手势 (就诊贴士)
    UITapGestureRecognizer *tipsTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tipsAction:)];
    [tipsTap setNumberOfTouchesRequired:1];
    [tipsPoint addGestureRecognizer:tipsTap];

    
}

#pragma mark    -------    手势 实现
//医院介绍
- (void)introduceAction:(UITapGestureRecognizer *)tap
{
    IntroduceViewController *introduce = [[IntroduceViewController alloc] init];
    introduce.introduce = self.hospital.introduce;
    [self.navigationController pushViewController:introduce animated:YES];
    
}

//就诊贴士
- (void)tipsAction:(UITapGestureRecognizer *)tap
{
    TipsViewController *tips = [[TipsViewController alloc] init];
    [self.navigationController pushViewController:tips animated:YES];
    
}

//查看路线
- (void)routeAction:(UITapGestureRecognizer *)tap
{
    if(self.startString)
    {
        //点击查看路线，将起始位置和终点位置传给系统
        [self didClickMap];
    }
    else
    {
        [self showLabelWithString:@"系统正在获取当前位置，请稍后再试" AndBlock:nil];
    }
    
}


- (void)detailsTableVIews
{
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"serviceCell"];
    
    self.hospitalArray = [NSMutableArray arrayWithArray:@[@"咨询医生",@"预约挂号",@"电子病历", ]];
    self.annotationArray = [NSMutableArray arrayWithArray:@[@"绑定您的主治医生,享受及时服务",@"提前预约,无需排队",@"查看排队情况,便捷出行"]];
    self.imageArray = [NSMutableArray arrayWithArray:@[@"H7.png",@"H10.png",@"H9.png"]];
    
}
//懒加载
- (NSMutableArray *)hospitalArray
{
    if (_hospitalArray == nil) {
        _hospitalArray = [NSMutableArray array];
    }
    return _hospitalArray;
    
}

//懒加载
- (NSMutableArray *)annotationArray
{
    if (_annotationArray == nil) {
        _annotationArray = [NSMutableArray array];
    }
    return _annotationArray;
    
}


//懒加载
- (NSMutableArray *)imageArray
{
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.hospitalArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   ServiceTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"serviceCell" forIndexPath:indexPath];
    
    cell.consultingLabel.text = self.hospitalArray[indexPath.row];
    cell.annotationLabel.text = self.annotationArray[indexPath.row];
    cell.hositeImage.image = [UIImage imageNamed:self.imageArray[indexPath.row]];
    return cell;
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = self.hospitalArray[indexPath.row];
    NSInteger index = [self.hospitalArray indexOfObject:str];
    [self pushViewControllerByIndex:index];
    
}

- (void)pushViewControllerByIndex:(NSInteger)index
{
    if([kShared.userType isEqualToString:@"普通用户"]||[kShared.userType isEqualToString:@"医生"])
    {
        switch (index)
        {
            case 0: //跳转到医生列表页
            {
                DoctorListViewController *doctorListVC = [DoctorListViewController new];
                doctorListVC.hospitalName = self.hospital.hospitalName;
                [self.navigationController pushViewController:doctorListVC animated:YES];
            }break;
            case 1:
            {
                if([kShared.userType isEqualToString:@"普通用户"])
                {
                    //跳转到挂号页面
                    RegisteredViewController *registered = [RegisteredViewController new];
                    registered.hospitalName = self.hospital.hospitalName;
                    [self.navigationController pushViewController:registered animated:YES];
                }
                else
                {
                    [self showLabelWithString:@"医生不可以挂号，请切换用户" AndBlock:nil];
                }
            }break;
            case 2: //跳转到电子病历页
            {
                MedicalRecordViewController *medicalRecordVC = [[MedicalRecordViewController alloc] init];
                [self.navigationController pushViewController:medicalRecordVC animated:YES];
            }break;
        }
    }
    else
    {   //如果没有登陆，先登陆
        [self showAlertTwoButtonWithTitle:@"提示" AndMessage:@"您还没有登陆，请先登陆" AndAlertStyle:UIAlertControllerStyleAlert AndOneButtonTitle:@"确定" AndTwoButtonTitle:@"取消" AndOneBlock:^{
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        } AndTwoBlock:nil];
    }
    
}

#pragma mark定位对象的代理方法实现
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    self.currentUserLocation = [locations lastObject];
    //每次定位完成之后，先停止定位
    [self.locationManager stopUpdatingLocation];
    [self reverseGecode];
}

//地理反编码。（根据经纬度，编码成地名)
- (void)reverseGecode
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:self.currentUserLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //取数组中第一个值，最准确
        CLPlacemark *mark = [placemarks firstObject];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.startString = mark.locality;
        });
    }];
}

//通过起始位置和终点位置得到两个CLPlacemark
- (void)didClickMap
{
    [self.geocoder geocodeAddressString:self.startString completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count == 0) return;
        
        CLPlacemark *startCLPlacemark = [placemarks firstObject];
        
        [self.geocoder geocodeAddressString:self.hospital.hospitalAddress completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count == 0) return;
            
            CLPlacemark *endCLPlacemark = [placemarks firstObject];
            
            [self startNavigationWithStartCLPlacemark:startCLPlacemark AndEndCLPlacemark:endCLPlacemark];
            
        }];
        
    }];
}

//调用系统的导航
- (void)startNavigationWithStartCLPlacemark:(CLPlacemark *)startCLPlacemark AndEndCLPlacemark:(CLPlacemark *)endCLPlacemark {
    //创建起点和终点
    MKPlacemark *startPlacemark = [[MKPlacemark alloc] initWithPlacemark:startCLPlacemark];
    
    MKPlacemark *endPlacemark = [[MKPlacemark alloc] initWithPlacemark:endCLPlacemark];
    
    
    MKMapItem *startItem = [[MKMapItem alloc] initWithPlacemark:startPlacemark];
    
    MKMapItem *endItem = [[MKMapItem alloc] initWithPlacemark:endPlacemark];
    
    NSArray *items = @[startItem,endItem];
    //调用系统自带的地图APP进行导航
    
    //设置启动参数
    NSMutableDictionary *md = [NSMutableDictionary dictionary];
    md[MKLaunchOptionsDirectionsModeKey] = MKLaunchOptionsDirectionsModeDriving;
    
    [MKMapItem openMapsWithItems:items launchOptions:md];
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
